package com.loongtech.bi.action.birealtime;

import com.loongtech.bi.action.TransferHelper;
import com.loongtech.bi.entity.system.EntityBiServer;
import com.loongtech.bi.manager.realTime.BossRealTimeManager;
import com.loongtech.bi.manager.realTime.ServerRealTimeManager;
import com.loongtech.bi.manager.realTime.ServerRealTimeManager.ServerRealTimeData;
import com.loongtech.bi.manager.realTime.ServerRealTimeManager.ServerRealTimeDetailData;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.support.chart.ChartTool;
import com.loongtech.bi.support.chart.ChartType;
import com.loongtech.bi.support.chart.ChartUIData;
import com.loongtech.core.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 
 * ClassName: ServerRealTimeBiAction
 * 
 * @Description: 实时数据-分服概况
 * @author liuchen
 * @date 2017-5-24 下午4:58:20
 */
@Controller
@Scope("prototype")
@RequestMapping("/realTime/serverRealTime")
public class ServerRealTimeBiAction extends TransferHelper {
	private static final long serialVersionUID = 1L;
	private Map<String, String> serverItmes; // 区服下拉列表

	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			List<EntityBiServer> list = BiPlatformManager.SERVER_LIST;
			serverItmes = new LinkedHashMap<>();
			for (int i = list.size() - 1; i >= 0; i--) {
				EntityBiServer t = list.get(i);
				serverItmes.put(t.getName(), t.getId());
			}
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@Autowired
	ServerRealTimeManager serverRealTimeManager;
	@Autowired
	BossRealTimeManager bossRealTimeManager;

	private List<ServerRealTimeDetailData> serverRealTimeDetailDatas; // 分服详细数据查询结果
	private ServerRealTimeDetailData allSumServerRealTimeDetailData; // 分服详细数据汇总结果
	private List<ServerRealTimeData> serverRealTimeDatas; // 分服实时在线数据

	private List<BossRealTimeManager.BossRealTimeDetailData> allDetailDatas; // 所有详细数据
	private List<BossRealTimeManager.BossRealTimeDetailData> detailDatas; // 前端要显示的详细数据
	private ChartUIData chartData; // 前端要显示的曲线图数据
	private ChartUIData serverRealTimeChart; // 分服实时在线图表

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String date,
			@RequestParam String eventTagId, @RequestParam String serverItmes, String callback) {
		serverRealTimeDatas = new ArrayList<>(); // 分服实时在线数据
		serverRealTimeDetailDatas = new ArrayList<>(); // 分服详细数据查询结果
		allSumServerRealTimeDetailData = serverRealTimeManager.new ServerRealTimeDetailData(); // 分服详细数据汇总结果
		serverRealTimeChart = null; // 分服实时在线图表
		try {
			List<String> selectedItems = serverItmes == null || "".equals(serverItmes) ? null : Arrays
					.asList(serverItmes.split(","));
			Map<String, Object> result = new HashMap<String, Object>();
			Date lookDate = Time.formatDate(date, "yyyy-MM-dd");
			// 分服详细数据
			serverRealTimeManager.updateServerRealTimeDetailData(lookDate, serverRealTimeDetailDatas,
					allSumServerRealTimeDetailData);

			// 分服实时数据
			serverRealTimeDatas = serverRealTimeManager.getServerRealTimeDatas(lookDate, selectedItems);
			if (serverRealTimeDatas != null && serverRealTimeDatas.size() > 0) {
				serverRealTimeChart = new ChartUIData();
				serverRealTimeChart.setSelectItem(eventTagId);
				serverRealTimeChart.setJsonStr(new ChartTool(serverRealTimeDatas, ServerRealTimeData.class,
						serverRealTimeChart.getSelectItem()).loadData(serverRealTimeChart.getJsonType()));
			} else {
				serverRealTimeChart = null;
			}

			allDetailDatas = bossRealTimeManager.getBossRealTimeDetailData(lookDate); // 详细数据
			selectItem(result);
			result.put("res", "0");
			for (ServerRealTimeDetailData data : serverRealTimeDetailDatas) {
				data.setServerid(BiPlatformManager.getServerNameById(data.getServerid()));
			}
			result.put("serverRealTimeDetailDatas", serverRealTimeDetailDatas);
			result.put("allSumServerRealTimeDetailData", allSumServerRealTimeDetailData);
			result.put("serverRealTimeChart", serverRealTimeChart);
			printToJson(response, result, callback);
		} catch (Exception e) {
			Map<String, Object> result = new HashMap<String, Object>();
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updateServerData.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateServerData(HttpServletRequest request, HttpServletResponse response, @RequestParam String date,
			@RequestParam String eventTagId, @RequestParam String serverItmes, String callback) {
		serverRealTimeDatas = new ArrayList<>(); // 分服实时在线数据
		serverRealTimeChart = null; // 分服实时在线图表
		try {
			List<String> selectedItems = serverItmes == null || "".equals(serverItmes) ? null : Arrays
					.asList(serverItmes.split(","));
			Map<String, Object> result = new HashMap<String, Object>();
			Date lookDate = Time.formatDate(date, "yyyy-MM-dd");

			// 分服实时数据
			serverRealTimeDatas = serverRealTimeManager.getServerRealTimeDatas(lookDate, selectedItems);
			if (serverRealTimeDatas != null && serverRealTimeDatas.size() > 0) {
				serverRealTimeChart = new ChartUIData();
				serverRealTimeChart.setSelectItem(eventTagId);
				serverRealTimeChart.setJsonStr(new ChartTool(serverRealTimeDatas, ServerRealTimeData.class,
						serverRealTimeChart.getSelectItem()).loadData(serverRealTimeChart.getJsonType()));
			} else {
				serverRealTimeChart = null;
			}
			result.put("serverRealTimeChart", serverRealTimeChart);
			printToJson(response, result, callback);
		} catch (Exception e) {
			Map<String, Object> result = new HashMap<String, Object>();
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	private String lastMaxOnlineNumStr = ""; // 前端要访问的当前最高负载：xx渠道xxx服xxxx人
	private String serverNumStr = ""; // 共xx组服务器

	private String selectedItem = "all"; // all=全部平台;ioszb=ios正版;hf=混服;yyb=应用宝;yhlm=硬核联盟

	public void selectItem(Map<String, Object> result) {
		if (allDetailDatas == null || allDetailDatas.size() <= 0) {
			detailDatas = null;
			chartData = null;
			lastMaxOnlineNumStr = "当前全服最高负载为0";
			serverNumStr = BossRealTimeManager.INDEX2NAME.get(selectedItem) + "共0组服务器"; // 服务器数量
			result.put("lastMaxOnlineNumStr", lastMaxOnlineNumStr);
			result.put("serverNumStr", serverNumStr);
			return;
		}

		Collections.sort(allDetailDatas, bossRealTimeManager.new BossRealTimeDetailData().comparatorOnlineReverse);
		BossRealTimeManager.BossRealTimeDetailData maxData = allDetailDatas.get(allDetailDatas.size() - 1);
		lastMaxOnlineNumStr = "当前全服最高负载：" + maxData.getItemName() + "渠道" + maxData.getServername() + "服"
				+ maxData.getOnlinenum() + "人";

		detailDatas = allDetailDatas;

		// 过滤未开放的服
		Iterator<BossRealTimeManager.BossRealTimeDetailData> iter = detailDatas.iterator();
		while (iter.hasNext()) {
			EntityBiServer s = BiPlatformManager.SERVER_MAP.get(iter.next().getServerid());
			if (s == null) {
				iter.remove();
			}
		}

		if (detailDatas != null && detailDatas.size() > 0) {
			serverNumStr = BossRealTimeManager.INDEX2NAME.get(selectedItem) + "共" + detailDatas.size() + "组服务器"; // 服务器数量

			chartData = new ChartUIData();
			chartData.setJsonType(ChartType.COLUMN.type);
			chartData.setJsonStr(new ChartTool(detailDatas.size() > 20 ? detailDatas.subList(detailDatas.size() - 20,
					detailDatas.size()) : detailDatas, BossRealTimeManager.BossRealTimeDetailData.class, chartData
					.getSelectItem()).loadData(chartData.getJsonType()));

			Collections.sort(detailDatas, bossRealTimeManager.new BossRealTimeDetailData().comparatorOnline);
		} else {
			serverNumStr = BossRealTimeManager.INDEX2NAME.get(selectedItem) + "共0组服务器"; // 服务器数量
			chartData = null;
		}
		result.put("lastMaxOnlineNumStr", lastMaxOnlineNumStr);
		result.put("serverNumStr", serverNumStr);
		result.put("chartData", chartData);
		result.put("detailDatas", detailDatas);
	}
}
